package com.atguigu.lease.interceptor;

import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.exception.leaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.mysql.cj.log.Log;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //在请求头中，获取token
        String access_token = request.getHeader("access-token");
        if(!StringUtils.hasText(access_token)){
            throw new leaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);//未登录
        }
        else{
            //解析token(对token作校验,token一旦过期或被篡改，就会抛对应的异常)
            Claims claims = JwtUtil.parseToken(access_token);
            //获取用户id
            Long userId = claims.get("userId", Long.class);
            //获取用户name
            String userName = claims.get("userName", String.class);
            //创建loginUser对象，只存储userId，userName
            LoginUser loginUser = new LoginUser(userId,userName);
            //怎么把该对象共享给我们的service或者controller呢，要用到ThreadLocal
            //为了在整个项目中当前线程可以在任意环节取出LoginUser，加了个ThreadLocal
           LoginUserContext.setThreadLocal(loginUser);
        }
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }
}
